<?php

namespace app\controllers;


use Seld\JsonLint\JsonParser;
use Seld\JsonLint\ParsingException;
use webignition\JsonPrettyPrinter\JsonPrettyPrinter;
use Yii;
use yii\web\MethodNotAllowedHttpException;
use zonday\weixin\api;
use zonday\weixin\exception\WeixinErrorException;

class MenuController extends BaseController
{
    public function actionIndex()
    {
        $apiMenu = new api\Menu;
        $request = Yii::$app->getRequest();
        if ($request->isPost && $menu = $request->post('menu')) {
            $parser = new JsonParser();
            $result = $parser->lint($menu);
            if ($result instanceof ParsingException) {
                $error = $result->getMessage();
            } else {
                $apiMenu->create($menu);
                Yii::$app->getSession()->setFlash('success', '更新微信餐单成功');
                return $this->refresh();
            }
        } else {
            try {
                $data = $apiMenu->get();
                $menu = json_encode($data['menu'], JSON_UNESCAPED_UNICODE);
            } catch (WeixinErrorException $e) {
                if ($e->getCode() == 46003) {
                    $menu = '{}';
                } else {
                    throw $e;
                }
            }
        }

        return $this->render('index', [
            'menu' => (new JsonPrettyPrinter)->format($menu),
            'error' => empty($error) ? '' : $error,
        ]);
    }

    public function actionDelete()
    {
        $request = Yii::$app->getRequest();
        if ($request->isPost) {
            $apiMenu = new api\Menu;
            $apiMenu->delete();
            Yii::$app->getSession()->setFlash('success', '删除微信餐单成功');
            return $this->refresh();
        } else {
            throw new MethodNotAllowedHttpException();
        }
    }
}
